package cn.edu.sdjzu.xg.bysj.service;


import cn.edu.sdjzu.xg.bysj.dao.PermissionDao;
import cn.edu.sdjzu.xg.bysj.security.Permission;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import cn.edu.sdjzu.xg.bysj.util.Condition;
import cn.edu.sdjzu.xg.bysj.util.JdbcHelper;
import cn.edu.sdjzu.xg.bysj.util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Collection;
import java.util.List;

public final class PermissionService {
	private static final PermissionDao PERMISSION_DAO = PermissionDao.getInstance();
	private static final PermissionService PERMISSION_SERVICE = new PermissionService();


	public static PermissionService getInstance() {
		return PERMISSION_SERVICE;
	}

	public Collection<Permission> findAll(Integer roleId) throws SQLException {
		//获取数据库连接
		Connection connection = JdbcHelper.getConn();
		Collection<Permission> permissions = PERMISSION_DAO.findAll(connection, roleId);
		//释放连接
		JdbcHelper.close(connection);
		return permissions;
	}

	public Collection<Permission> findAll(Pagination pagination, List<Condition> conditionList) throws SQLException {
		//获取数据库连接
		Connection connection = JdbcHelper.getConn();
		Collection<Permission> permissions = PERMISSION_DAO.findAll(connection, pagination, conditionList);
		//释放连接
		JdbcHelper.close(connection);
		return permissions;

	}

	public Permission find(Integer id) throws SQLException {
		//获取数据库连接
		Connection connection = JdbcHelper.getConn();
		Permission permission = PERMISSION_DAO.find(connection, id);
		//释放连接
		JdbcHelper.close(connection);
		return permission;
	}

	public boolean update(Permission permission) throws SQLException {
		//获取数据库连接
		Connection connection = JdbcHelper.getConn();
		boolean updated = PERMISSION_DAO.update(connection, permission);
		//释放连接
		JdbcHelper.close(connection);
		return updated;
	}

	public boolean add(Permission permission) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		boolean added = PERMISSION_DAO.add(connection, permission);
		JdbcHelper.close(connection);
		return added;
	}

	public boolean delete(Integer id) throws SQLException, BysjException {
		//获取数据库连接
		Connection connection = JdbcHelper.getConn();
		boolean deleted = false;
		try {
			deleted = PERMISSION_DAO.delete(connection, id);
			return deleted;
		} catch (SQLIntegrityConstraintViolationException e) {
			throw new BysjException("某角色正在使用当前资源");
		} finally {
			//释放连接
			JdbcHelper.close(connection);
		}

	}
}
